const path = require('path');
const webpack = require('webpack');
const ROOT = process.cwd(); // 根目录
const ENV = process.env.NODE_ENV;
const IsProduction = (ENV === 'production') ? true : false;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PostcssConfigPath = './config/postcss.config.js';
const Glob = require('glob');
const HappyPack = require('happypack');
const HappyThreadPool = HappyPack.ThreadPool({ size: (IsProduction ? 10 : 4) });
const CopyWebpackPlugin = require('copy-webpack-plugin');
const staticUrl = '//cdn.com';
const publicPath = IsProduction ? staticUrl : '/';
const extraPath = IsProduction ? '/' : '';


let entryHtml = getEntryHtml('./src/view/**/*.html'),
    entryJs = getEntry('./src/js/**/*.js'),
    configPlugins = [
        new HappyPack({
            id: 'js',
            threadPool: HappyThreadPool,
            loaders: ['babel-loader']
        }),
        new HappyPack({
            id: 'styles',
            threadPool: HappyThreadPool,
            loaders: ['style-loader', 'css-loader', 'less-loader', 'postcss-loader']
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'common'
        }),
        new ExtractTextPlugin({
            filename: 'css/[name].css?[contenthash:8]',
            allChunks: true
        }),
        // 手动 copy 一些文件
        // new CopyWebpackPlugin([{
        //     from: ['src/js/lib/queries.min.js', 'src/js/lib/main.js'],
        //     to: ['js/lib/queries.min.js', 'js/lib/main.js']
        // }]),
        new webpack.ProvidePlugin({
            jQuery: 'jquery',
            $: 'jquery'
        })
    ];

// html
entryHtml.forEach(function(v) {
    configPlugins.push(new HtmlWebpackPlugin(v));
});

// 开发环境不压缩 js
if (IsProduction) {
    configPlugins.push(new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        }
    }));
}


// 配置
const config = {
    entry: entryJs,
    output: {
        filename: 'js/[name].js?[chunkhash:8]',
        chunkFilename: 'js/[name].js?[chunkhash:8]',
        path: path.resolve(ROOT, 'dist'),
        publicPath: publicPath
    },
    module: {
        rules: [{
                test: /\.js$/i,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader?id=js',
                    options: {
                        presets: ['env'],
                        // presets: ['es2015', { modules: false }],

                    }
                }
            },
            {
                test: /\.(less|css)$/i,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader?id=styles',
                    use: [{
                            loader: 'css-loader?id=styles',
                            options: {
                                minimize: IsProduction
                            }
                        },
                        {
                            loader: 'less-loader?id=styles'
                        },
                        {
                            loader: 'postcss-loader?id=styles',
                            options: {
                                config: {
                                    path: PostcssConfigPath
                                }
                            }
                        }
                    ]
                })
            },
            {
                test: /\.(png|jpe?g|gif|svg)$/i,
                use: [{
                        loader: 'url-loader',
                        options: {
                            limit: 100,
                            publicPath: publicPath + extraPath,
                            name: 'img/[name].[ext]?[hash:8]'
                        }
                    },
                    {
                        loader: 'image-webpack-loader',
                        query: {
                            mozjpeg: {
                                quality: 65
                            },
                            pngquant: {
                                quality: '65-90',
                                speed: 4
                            }
                        }
                    }
                ]
            },
            {
                test: /\.(eot|svg|ttf|woff)$/i,
                use: [{
                    loader: 'url-loader',
                    options: {
                        limit: 100,
                        publicPath: publicPath + extraPath,
                        name: 'font/[name].[ext]?[hash:8]'
                    }
                }]
            },
            {
                test: /\.(htm|html|art)$/i,
                loader: 'art-template-loader',
                options: {}
            },
            // {
            //     test: /\.(htm|html)$/i,
            //     loader: 'html-withimg-loader?min=false'
            // }


        ]
    },
    resolve: {
        alias: {
            views: path.resolve(ROOT, './src/view'),
            metisMenu: path.resolve(ROOT, './srv/js/conmons/metisMenu/'),

        },
        extensions: ['.js', '.css', '.less'],
    },
    plugins: configPlugins,
    devServer: {
        contentBase: [
            path.join(ROOT, 'src/')
        ],
        disableHostCheck: true,
        hot: false,
        host: 'localhost',
        port: 8080,
        proxy: [{
            context: ['/api/'],
            target: 'http://192.168.1.10:8000',
            secure: false
        }]
    }
};

/**
 * 根据目录获取入口
 * @param  {[type]} globPath [description]
 * @return {[type]}          [description]
 */
function getEntry(globPath) {
    let entries = {};
    Glob.sync(globPath).forEach(function(entry) {
        let basename = path.basename(entry, path.extname(entry)),
            pathname = path.dirname(entry);
        // js/lib/*.js 不作为入口
        if (!entry.match(/\/js\/(lib|commons)\//)) {
            entries[pathname.split('/').splice(3).join('/') + '/' + basename] = pathname + '/' + basename;
        }
    });
    return entries;
}

/**
 * 根据目录获取 Html 入口
 * @param  {[type]} globPath [description]
 * @return {[type]}          [description]
 */
function getEntryHtml(globPath) {
    let entries = [];
    Glob.sync(globPath).forEach(function(entry) {
        let basename = path.basename(entry, path.extname(entry)),
            pathname = path.dirname(entry),
            minifyConfig = !IsProduction ? '' : {
                removeComments: true,
                collapseWhitespace: true,
                minifyCSS: true,
                minifyJS: true
            };

        entries.push({
            filename: entry.split('/').splice(2).join('/'),
            template: entry,
            chunks: ['common', pathname.split('/').splice(3).join('/') + '/' + basename],
            minify: minifyConfig
        });

    });
    return entries;
}

module.exports = config;